package com.fjd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fjd.constant.MessageConstant;
import com.fjd.context.BaseContext;
import com.fjd.dto.CustomerDTO;
import com.fjd.dto.LoginDTO;
import com.fjd.dto.PCLoginDTO;
import com.fjd.entity.CustomerInfo;
import com.fjd.exception.LoginFailedException;
import com.fjd.mapper.ShoppingCustomerInfoMapper;
import com.fjd.properties.WeChatProperties;
import com.fjd.service.CustomerService;
import com.fjd.utils.HttpClientUtil;
import com.fjd.vo.CustomerVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private ShoppingCustomerInfoMapper shoppingCustomerInfoMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    //微信登录接口的 URL
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    private static final String DEFAULT_AVATAR="https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";
    /**
     * 微信登录
     * @param loginDTO
     * @return
     */
    public CustomerInfo login(LoginDTO loginDTO) {
        log.info("微信登录，code:{}",loginDTO.getCode());
        String openid = getOpenId(loginDTO.getCode());
        log.info("openid:{}",openid);
        //判断openId是否为空，如果为空，登录失败，抛出业务异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        CustomerInfo customerInfo = shoppingCustomerInfoMapper.getByOpenId(openid);
        //如果是新用户，自动注册
        if (customerInfo == null) {
            customerInfo = CustomerInfo.builder()
                    .openId(openid)
                    .customerId(UUID.randomUUID().toString().replace("-",""))
                    .customerAvatar(DEFAULT_AVATAR)
                    .build();
            shoppingCustomerInfoMapper.insert(customerInfo);
        }
        return customerInfo;
    }

    private String getOpenId(String code) {
        //调用微信服务器接口，获取当前用户openId
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        //发送请求
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
    public CustomerInfo weblogin(PCLoginDTO loginDTO) {
        log.info("网页登录");
        //判断当前用户是否为新用户
        Integer customer_id = shoppingCustomerInfoMapper.findByAccount(loginDTO.getUsername(), loginDTO.getPassword());
        if (customer_id == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        System.out.println(customer_id);
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo = shoppingCustomerInfoMapper.getByCustomerId(customer_id);
        if (customerInfo == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return customerInfo;
    }

    /**
     * 获取用户头像和昵称
     * @return
     */
    public CustomerVO getInfo() {
        String customerId = String.valueOf(BaseContext.getCurrentId());
        CustomerInfo customerInfo = shoppingCustomerInfoMapper.getAvatarAndNickname(customerId);
        CustomerVO customerVO = new CustomerVO();
        BeanUtils.copyProperties(customerInfo, customerVO);
        return customerVO;
    }

    /**
     * 编辑用户头像和昵称
     * @param customerDTO
     */
    public void editById(CustomerDTO customerDTO) {
        CustomerInfo customerInfo = new CustomerInfo();
        BeanUtils.copyProperties(customerDTO, customerInfo);
        customerInfo.setCustomerId(String.valueOf(BaseContext.getCurrentId()));
        log.info("编辑用户信息:{}",customerInfo);
        shoppingCustomerInfoMapper.updateById(customerInfo);
    }

    public CustomerInfo getAllInfo() {
        CustomerInfo customerInfo = shoppingCustomerInfoMapper.getByCustomerId(Integer.valueOf(BaseContext.getCurrentId()));
        return customerInfo;
    }
}
